<?php
namespace app\kaoqin\controller;

use api\auth\Auth;
use api\auth\Token;
use my\wechat\QyWeChat;

class Open
{
    private $_wechat = null;

    private function wechat()
    {
        $c = [
            'appid' => c('wx_appid'),
            'appsecret' => c('wx_appsecret')
        ];

        if ($this->_wechat == null)
            $this->_wechat = new QyWeChat($c);

        return $this->_wechat;
    }

    public function login()
    {
        if (config('app_is_release')) {
            return $this->checkOAuth();
        }

        return view();
    }

    private function checkOAuth()
    {
        $code = input('code');
        if (!empty($code)) {
            //获取微信企业号通讯录信息
            $member_info = $this->wechat()->getUserId($code);

            $uid = '';
            $timeout = 0;

            //授权用户是微信企业号成员
            if (isset($member_info['UserId'])) {
                $uid = $member_info['UserId'];
                $timeout = 10 * 365 * 24 * 60 * 60;
            }

            //授权用户不是微信企业号成员
            if (isset($member_info['OpenId'])) {
                $uid = $member_info['OpenId'];
                $timeout = 2 * 60 * 60;
            }

            //记住用户
            cookie("UID", Auth::auth_encrypt($uid), $timeout);
            if (config('app.is_remote')) {
                $token = Token::update_token($uid, $timeout);
                cookie("token", $token, $timeout);
            }

            $callback = cookie('login_callback');
            cookie('login_callback', null);

            return redirect($callback);
        }

        //登录成功回调地址
        $callback = input('server.HTTP_REFERER');
        cookie('login_callback', $callback);

        $current_url = request()->url(true);
        $redirect_url = $this->wechat()->getOauthRedirect($current_url);
        return redirect($redirect_url);
    }


    public function cache()
    {
        cookie("UID", null);

        return redirect(url('record/me'));

    }
}
